package com.cfushn.ddd.catchlog;

import com.cfushn.ddd.application.dto.res.ResDTO;
import com.cfushn.ddd.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

/**
 * DefaultErrorResponseHandler
 * 检查返回值是否是ResultVo, 如果是, 则返回ResultVo.failed; 否则不予处理
 *
 * @author CFuShn 2023/3/28 20:09
 */
@Slf4j
public class DefaultErrorResponseHandler implements ErrorResponseHandlerI {

    public Object handle(Class<?> returnType, BaseException e) {
        return handle(returnType, e.getErrCode(), e.getMessage());
    }

    @Override
    public Object handle(Class<?> returnType, String errCode, String errMsg) {
        if (isResponse(returnType)) {
            try {
                return ResDTO.failed(null, errCode, errMsg);
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
                return null;
            }
        }
        return null;
    }

    private static boolean isResponse(Class<?> returnType) {
        return returnType == ResDTO.class || returnType.getGenericSuperclass() == ResDTO.class;
    }
}
